package com.tang.websocket.v1;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Tang
 * @classname ConverterRegistry
 * @description [  ]
 * @date 2022/11/28 21:40
 */
@Component
public class ConverterRegistry {

    private List<Converter<?,?>> converterList = new ArrayList<>();

    public <T,R> void addConverter(Converter<T,R> converter) {
        this.converterList.add(converter);
    }

    public <T,R> void removeConverter(Converter<T,R> converter) {
        this.converterList.remove(converter);
    }

    public void removeConverter(Class<?> sourceClass,Class<?> targetClass) {
        List<Converter<?,?>> qualifiedConverterList = new ArrayList<>();
        for (Converter<?,?> trConverter : this.converterList) {
            if (selectConverter(sourceClass, targetClass) == null) {
                qualifiedConverterList.add(trConverter);
            }
        }
        this.converterList = qualifiedConverterList;
    }

    public <T,R> Converter<T,R> selectConverter(Class<?> sourceClass,Class<?> targetClass) {
        for (Converter<?,?> trConverter : converterList) {
            if (trConverter.isSupport(sourceClass, targetClass)) {
                return (Converter<T, R>) trConverter;
            }
        }
        return null;
    }

}
